import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store";

// 安装插件
Vue.use(VueRouter);

// 创建路由并配置
const Rout = new VueRouter({
  mode: "history", // 路由的模式
  routes: [
    // 路由的配置集合
    {
      path: "/", // 首页
      name: "home", // 路由的名字
      meta: { name: "home" },
      component: () => import("../views/Home.vue")
    },
    // 列表路由
    {
      path: "/list/:id",
      name: "list",
      // meta这是一个路由内置的，允许咱们自定义的数据
      meta: { keepAlive: true },
      component: () => import("../views/list")
    },
    // 产品详情
    {
      path: "/detail/:id",
      name: "detail",
      component: () => import("../views/detail")
    },
    // 提交订单
    {
      path: "/submit/:id",
      name: "submit",
      component: () => import("../views/sumbitBarBox")
    },
    // 购物车
    {
      path: "/shop",
      name: "shop",
      component: () => import("../views/shop")
    },
    // 订单
    {
      path: "/balance",
      name: "balance",
      component: () => import("../views/balance")
    },
    // 用户我的界面
    {
      path: "/user",
      name: "user",

      component: () => import("../views/user")
    },
    {
      //我的
      path: "/mine",
      name: "mine",
      component: () => import("../views/mine")
    },
    {
      path: "/login", // 登陆
      name: "login",
      meta: { name: "user" },
      component: () => import("../views/login")
    },
    {
      // 当我们的路由进入了不存在的地址的时候，重定向回首页
      path: "*",
      redirect: "/"
    }
  ]
});
// 路由守卫--拦截--前置守卫：进入路由前

Rout.beforeEach((to, from, next) => {
  // user.loginState 它是接口返回的用户登陆状态
  let state = store.state.user.loginState;

  // 订单页没登陆去登陆页
  if (to.name === "balance" && !state) {
    next("/login");
  } else if (to.name === "shop" && !state) {
    next("/login");
  } else {
    next();
  }
});
// 暴露
export default Rout;
